package com.pod5.skype.backup;

import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.io.*;
import java.nio.channels.spi.*;
import java.nio.charset.*;
import java.util.LinkedList;
import java.lang.*;


public class BackupClient
{
    public SocketChannel client = null;
    public InetSocketAddress isa = null;
    private Boolean stop = false;
    public RecvThread rt = null;
    private String connectionIp;
    private Writer backupData;
    private int state = 0;
    
	private File rawIPDataFile;
	private File readableIPFile;
	private File crawledIPFile;
	

    
    private LinkedList<String> masterList;
    

    public BackupClient()
    {
    	masterList = new LinkedList<String>();
    	masterList.add("192.168.1.183");
		rawIPDataFile = new File("rawIPDataFile.b");
		readableIPFile = new File("readableIPFile.b");
		crawledIPFile = new File("crawledIPFile.b");
		if(!rawIPDataFile.exists() || !readableIPFile.exists() || !crawledIPFile.exists())
		{
			try {
				rawIPDataFile.createNewFile();
				readableIPFile.createNewFile();
				crawledIPFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    }
    
	public void makeConnection()
    {
			setupConnection();
			receiveMessage();
			while (!stop)
			{
				try {
					if(state == 0)
					{
						backupData = new BufferedWriter(new FileWriter(rawIPDataFile));
						sendMessage("rawIPDataFile");
					}
					else if (state == 1)
					{
						backupData = new BufferedWriter(new FileWriter(readableIPFile));
						sendMessage("readableIPFile");
					}
					else
					{
						backupData = new BufferedWriter(new FileWriter(crawledIPFile));
						sendMessage("crawledIPFile");
					}
					state = (state+1)%3;
					System.out.println(state);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				try {
					Thread.sleep(1000*60);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			interruptThread();



		try
		{
			client.close();
			System.exit(0);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
    }
	
	private void setupConnection(){
		if(!masterList.isEmpty())
		{
			connectionIp = masterList.remove();
			try
			{
				client = SocketChannel.open();
				isa = new InetSocketAddress(connectionIp, 5051);
				client.connect(isa);
				client.configureBlocking(false);
			}
			catch(UnknownHostException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}

		}
		else
			stop = true;
	}
    
	public void sendMessage(String msg)
    {
		System.out.println("Inside SendMessage");
        ByteBuffer bytebuf = ByteBuffer.allocate(1024);
		int nBytes = 0;
		try
		{
				bytebuf = ByteBuffer.wrap(msg.getBytes());
				nBytes += client.write(bytebuf);
				System.out.println("nBytes is "+nBytes);

				bytebuf.clear();

			System.out.println("nBytes is "+nBytes);

			bytebuf.clear();
	    
		}
        catch(IOException e)
		{
			e.printStackTrace();
			System.out.println("Extablishing a connection with a different Host, wait 4 mins before attempting");

			
		}
		System.out.println("Wrote "+nBytes +" bytes to the server");
		
    }

    public static void main(String args[])
    {
//    	Client cl = new Client(System.getenv("HOME")+"/.Skype/shared.xml"); //For Linux
		BackupClient cl = new BackupClient();
		cl.makeConnection();
    }

    public void receiveMessage()
    {
		rt = new RecvThread("Receive THread",client);
		rt.start();

    }

    public void interruptThread()
    {
		rt.val = false;
    }
    
    public class RecvThread extends Thread
    {
		public SocketChannel sc = null;
		public boolean val = true;
	
		public RecvThread(String str,SocketChannel client)
		{
			super(str);
			sc = client;
		}
	
		public void run() {

			System.out.println("Inside receivemsg");
			ByteBuffer buf = ByteBuffer.allocate(1024);
			try
			{
				while (val)
				{
						while ( (client.read(buf)) > 0 ){
							buf.flip();
							Charset charset = Charset.forName("us-ascii");
							CharsetDecoder decoder = charset.newDecoder();
							CharBuffer charBuffer = decoder.decode(buf);
							backupData.write(charBuffer.toString());
							
							buf.clear();

						}
				}
			
			}
			catch(IOException e)
			{
				e.printStackTrace();
				System.out.println("Backup Enitiated");
				stop = true;
			}
            

		}
    }
    
}
